<template>
  <div class="knowledge" @touchend="active = false">
    <div v-if="dataLiat.length <= 0" class="default-header">
      <div class="card">
        <h3>Hi，我是你的<span>AI助手</span>～</h3>
        <p>快速精准地查找用户指定或描述的文件，提升查找效率并简化文件管理流程。</p>
        <div><span></span>个性化</div>
        <div><span></span>知识管理</div>
        <div><span></span>内容整合</div>
      </div>
    </div>
    <div v-else class="body">
      <div :class="item.type ? 'body-it' : 'body-my'" v-for="item, index in dataLiat">
        <SvgIcon v-if="!item.type" name="头像" class="my-img" :size="28" />
        <SvgIcon v-if="item.type" name="AI助手" class="it-img" :size="28" />
        <SvgIcon v-if="item.message.length <= 0" name="load" class="load" :size="20" />
        <span v-else v-html="item.message">
        </span>
        <van-button @click="regenerate(index)" v-if="item.type && item.message.length > 0" class="Regenerate btn">
          <SvgIcon name="刷新" :size="16" />
          重新生成
        </van-button>
        <van-button v-if="item.type && item.message.length > 0" @click="palySuspend(item.message)"
          class="Rebroadcast btn">
          <SvgIcon :name="isPalySuspend ? '播放' : '暂停'" :size="16" />
          <div ref="shu" class="shu">
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
          </div>
        </van-button>
      </div>
    </div>
    <van-field class="search" placeholder="输入问题尽管问我吧" v-model="search">
      <template #right-icon>
        <div class="search-icon">
          <SvgIcon v-show="search.length !== 0" @click="search = ''" class="icon-item" name="清空" :size="24" />
          <SvgIcon :class="`icon-item ${active ? 'active' : ''}`" @touchstart="onTouch" name="麦克风" :size="16" />
          <van-button @click="querysubmit" style="width: 24px;height: 31px;" type="primary">
            <SvgIcon name="飞机" :size="16" />
          </van-button>
        </div>
      </template>
    </van-field>
  </div>
</template>

<script setup>
import SvgIcon from "@/components/SvgIcon.vue";
import { query } from "@/api/index"
import { ref, onMounted, computed, watch } from "vue"
const search = ref('')
const active = ref(false)
const isSetInterval = ref(0)
const isPalySuspend = ref(true)
const str = ref('')
const newStr = ref('')
const utterance = ref(null)
const dataLiat = ref([])
const shu = ref(null)
const querysubmit = async () => {
  const message = search.value
  search.value = ""
  if (search.length <= 0) return
  dataLiat.value.push({
    type: 0,
    message
  })
  const itOBJ = ref({
    type: 1,
    message: ''
  })
  dataLiat.value.push(itOBJ.value)
  setTimeout(() => {
    document.querySelector('.knowledge').scrollTo(0, document.querySelector('.knowledge').scrollHeight);
  }, 10)
  try {
    const res = await query(message)
    str.value = res
  } catch (error) {
    itOBJ.value.message = '网络出错！'
  } finally {
    setTimeout(() => {
      itOBJ.value.message = newStr.value
      document.querySelector('.knowledge').scrollTo(0, document.querySelector('.knowledge').scrollHeight);
    }, 10)
  }

}

const onTouch = () => {
  active.value = true
  AndroidInterface.startListening()
}

watch(str, (v) => {
  if(!str.value.includes("无法回答")){
    newStr.value = str.value.split('data:').reduce((str, item) => {
      return item.length > 0 ? str + JSON.parse(item)?.message : str
    }, '')
  }
})

const handleRecognitionResult = (data) => {
  search.value = data
}
const regenerate = async (index) => {
  const message = dataLiat.value[index - 1].message
  dataLiat.value[index].message = ""
  try {
    const res = await query(message)
    str.value = res

  } catch (error) {
    dataLiat.value[index].message = '网络出错！'
    console.log('网络出错！')
  }finally {
    setTimeout(() => {
      dataLiat.value.splice(index, 1)
      dataLiat.value.push({
        type: 1,
        message: newStr.value
      })
      document.querySelector('.knowledge').scrollTo(0, document.querySelector('.knowledge').scrollHeight);
    }, 10)
  }
}


const palySuspend = (data) => {
  isPalySuspend.value = !isPalySuspend.value
  if (!isPalySuspend.value) {
    speechSynthesis.cancel();
    // utterance.value = new SpeechSynthesisUtterance(data);
    // speechSynthesis.speak(utterance.value);
    AndroidInterface.speak(data)
    // 等待音频播放完成
    // utterance.value.onend = function () {
    //   console.log('bofang wanbi')
    //   // 在这里可以执行重新播放的操作
    //   speechSynthesis.cancel();
    //   isPalySuspend.value = true
    //   isSetInterval.value && clearInterval(isSetInterval.value)
    //   // utterance.play(); // 重新播放音频
    // };
    let i = 0
    Array.from(shu.value[0].children).forEach((item) => {
      item.style.height = 2
    })
    isSetInterval.value = setInterval(() => {
      if (i === 13) i = 0
      let arr = [[0, 8], [2, 14], [3, 20], [5, 8]]
      for (let j = 0; j < shu.value[0].children.length; j++) {
        shu.value[0].children[j].style.height = 4 + 'px'
      }

      if (i >= 11) {
        arr.splice(arr.length - 1, 1)
      }
      arr.forEach((ele) => {

        shu.value[0].children[ele[0] + i].style.height = ele[1] + 'px'
      })
      if (i >= 11) {
        shu.value[0].children[shu.value[0].children.length - 1].style.height = 2 + "px"
      }
      i++
    }, 90)
  } else {
    isSetInterval.value && clearInterval(isSetInterval.value)
  }
}
</script>

<style lang="scss" scoped>
.knowledge {
  padding-bottom: 60px;

  .default-header {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 16px;

    .card {
      width: 343px;
      height: 210px;
      border-radius: 16px;
      background-color: #fff;
      padding: 16px;
      color: #191919;

      h3 {
        font-size: 17px;

        span {
          color: var(--van-primary-color)
        }
      }

      p {
        font-family: "PingFang SC";
        font-size: 14px;
        margin: 12px 0;
      }

      div {
        font-size: 14px;
        display: flex;
        align-items: center;
        margin: 10px 0;

        span {
          width: 5px;
          height: 5px;
          border-radius: 50%;
          background-color: var(--van-primary-color);
          margin-right: 8px;
        }
      }
    }
  }

  .body {
    padding: 16px;
    display: flex;
    flex-direction: column;
  }

  .body-my {
    border-radius: 12px;
    background: var(--van-primary-color);
    width: fit-content;
    padding: 12px 16px;
    font-size: 14px;
    color: #fff;
    margin: 24px 0;
    margin-left: auto;
    position: relative;
    border-radius: 10px 0 10px 10px;

    .my-img {
      position: absolute;
      right: 0;
      top: -30px;
    }
  }

  .body-it {
    position: relative;
    border-radius: 12px;
    width: fit-content;
    padding: 12px 16px;
    font-size: 14px;
    background-color: #fff;
    margin: 24px 0;
    position: relative;
    margin-bottom: 50px;
    margin-right: auto;
    border-radius: 0 10px 10px 10px;

    .load {
      animation: rotate 1s linear infinite;
    }

    .it-img {
      position: absolute;
      left: 0;
      top: -30px;
    }

    .btn {
      position: absolute;
      border-radius: 16px;
      border: 0.75px solid #DBDCE0;
      background-color: transparent;
      height: 30px;
      color: #333;
      font-size: 12px;
      bottom: -40px;
      padding-left: 10px;
      padding-right: 10px;

      :deep(.van-button__text) {
        display: flex;
      }
    }

    .Regenerate {
      width: 88px;

      left: 0;

    }

    .Rebroadcast {
      left: 100px;
      width: 100px;

      .shu {
        display: flex;
        width: 64px;
        height: 20px;
        margin-left: 3px;
        align-items: center;

        span {
          transition: all 0.1s;
          display: flex;
          // width: 2px;
          // height: 4px;
          // border: none;
          margin-right: 2px;
          border-radius: 1px;
          width: 2px;
          height: 4px;
          background-color: #555;

          &:nth-child(7),
          &:nth-child(12) {
            height: 8px;
          }

          &:nth-child(9) {
            height: 14px;
          }

          &:nth-child(10) {
            height: 20px;
          }
        }
      }
    }
  }

  .search {
    position: fixed;
    bottom: 2px;
    height: 52px;
    font-size: 14px;
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 8px;
    background: #FFF;
    box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.12);

    .search-icon {
      display: flex;
      align-items: center;
      justify-content: center;

      .icon-item {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;

        color: #fff;

        &:nth-child(2) {
          border-radius: 50%;
          padding: 4px;
          color: #000000;
          transition: 1s;
        }
      }

      .active {
        background-color: var(--van-primary-color);
        color: #fff !important;
      }
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>
